package com.daguchuangyi.erp_android.production_detail;

import android.app.Application;
import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.TransStatusBarActivity;
import com.daguchuangyi.erp_android.manager.NetworkManager;
import com.daguchuangyi.erp_android.manager.networkservice.ProductService;
import com.daguchuangyi.erp_android.model.product.Parameter;
import com.daguchuangyi.erp_android.model.product.Photo;
import com.daguchuangyi.erp_android.model.product.Product;
import com.daguchuangyi.erp_android.model.product.Shelf;
import com.daguchuangyi.erp_android.model.product.Storage;
import com.daguchuangyi.erp_android.production_detail.widget.ProductCoverView;
import com.daguchuangyi.erp_android.production_detail.widget.ProductDetailSectionView;
import com.daguchuangyi.erp_android.productlist.ProductSummaryManager;
import com.daguchuangyi.erp_android.productlist.ProductionSummaryActivity;
import com.daguchuangyi.erp_android.productlist.classifiaction.ClassificationManager;
import com.daguchuangyi.erp_android.productlist.select.SelectProductActivity;
import com.daguchuangyi.erp_android.util.ErrorHandler;
import com.flyco.tablayout.SlidingTabLayout;
import com.jude.utils.JUtils;
import com.kaopiz.kprogresshud.KProgressHUD;

import net.cachapa.expandablelayout.ExpandableLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

import static com.raizlabs.android.dbflow.config.FlowManager.getContext;

public class ProductDetailActivity extends TransStatusBarActivity implements ProductSummaryManager.OnProductCheckChangeListenner {
    private static final String TAG = ProductDetailActivity.class.getSimpleName();

    public static final String TAG_PRODUCT = "TAG_PRODUCT";
    public static final String TAG_ID_PRODUCT = "TAG_ID_PRODUCT";

    private Product mProduct;
    private List<Storage> mStorageList;
    private int mProductId;

    private ViewPager mContentViewPager;
    private SlidingTabLayout mTabLayout;
    private ContentPagerAdapter mPagerAdapter;
//    private View mTopShadowView;

    private TextView mToggleTv;
    private ImageView mExpandHintIv;
    private ExpandableLayout mExpandableLayout;
    private View mToggleWrapper;
    private ProductCoverView mProductCoverView;
    private TextView mTitleTv;
    private TextView mProductSerialNumTv;

    private TextView mDiffTv;
    private TextView mSatificationTv;

    private ViewGroup mDownloadWrapper;

    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();

    public static void start(Context context, int productId) {
        JUtils.Log(TAG, "start with product ID : " + productId);
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra(TAG_ID_PRODUCT, productId);
        if (context instanceof Service || context instanceof Application) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void start(Context context, Product product) {
        Intent intent = new Intent(context, ProductDetailActivity.class);
        intent.putExtra(TAG_PRODUCT, product);
        if (context instanceof Service || context instanceof Application) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_detail);
        setStatusBarFontIconDark(true);


        mProduct = getIntent().getParcelableExtra(TAG_PRODUCT);
        mProductId = getIntent().getIntExtra(TAG_ID_PRODUCT, -1);

//        mTopShadowView = findViewById(R.id.detail_top_shadow);
        AppBarLayout mAppBarLayout = (AppBarLayout) findViewById(R.id.app_bar_layout);
        View actionBar = findViewById(R.id.action_bar);
        mTitleTv = mAppBarLayout.findViewById(R.id.page_title_tv);
        View bottomLine = mAppBarLayout.findViewById(R.id.title_bottom_line);
        mProductCoverView = mAppBarLayout.findViewById(R.id.product_cover_view);
        mProductSerialNumTv = (TextView) findViewById(R.id.product_serial_num_tv);
        ImageView backIv = (ImageView) findViewById(R.id.back_icon_iv);
        backIv.setImageResource(R.drawable.white_back);
        backIv.setOnClickListener(v -> finish());

        findViewById(R.id.temp_folder_wrapper).setOnClickListener(v -> {
            Intent intent = new Intent(ProductDetailActivity.this, SelectProductActivity.class);
            startActivity(intent);
        });

        mAppBarLayout.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
                    int totalScrollRange = appBarLayout.getTotalScrollRange();
                    float progress = ((float) Math.abs(verticalOffset) / totalScrollRange);
                    JUtils.Log("progress is : " + progress);
                    if (progress > 1.0) {
                        return;
                    }
                    if (progress > 0.5) {
                        backIv.setImageResource(R.drawable.dark_back);
                    } else {
                        backIv.setImageResource(R.drawable.white_back);
                    }
                    if (progress > 0.8) {
                        bottomLine.setVisibility(View.VISIBLE);
                        mTitleTv.setTextColor(Color.parseColor("#4e5565"));
                        setStatusBarFontIconDark(true);
                        actionBar.setBackgroundColor(changeAlpha(Color.WHITE, Math.abs(progress)));
                    } else {
                        setStatusBarFontIconDark(false);
                        bottomLine.setVisibility(View.GONE);
                        mTitleTv.setTextColor(Color.WHITE);
//                        mTopShadowView.setVisibility(View.VISIBLE);
                        actionBar.setBackgroundResource(R.drawable.detail_cover_shadow);
                    }
                    mTitleTv.setAlpha(progress);
                }
        );

        mSatificationTv = (TextView) findViewById(R.id.satification_tv);
        mSatificationTv.setOnClickListener(view -> {

            final KProgressHUD hubDialog = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setCancellable(false)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f)
                    .show();

            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("productId", mProduct.getId());
            Subscription subscription = NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                    .sendSatificationFeedback(queryMap)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(resultMap -> {
                        hubDialog.dismiss();
                        if (resultMap.keySet().contains("msg")) {
                            JUtils.ToastLong(resultMap.get("msg"));
                        }
                    }, throwable -> {
                        hubDialog.dismiss();
                        String errorMsg = "发送反馈失败,请检查网络连接";
                        ErrorHandler.handlerNetworError(throwable, errorMsg);
                        JUtils.Log("发送反馈失败：" + throwable.getMessage());
                        throwable.printStackTrace();
                    });
            mCompositeSubscription.add(subscription);
        });
        mToggleTv = (TextView) findViewById(R.id.toggle_tv);

        mExpandHintIv = (ImageView) findViewById(R.id.expand_hint_iv);

        mExpandableLayout = (ExpandableLayout) findViewById(R.id.expandable_layout);
        mExpandableLayout.setOnExpansionUpdateListener((expansionFraction, state) -> {
            if (state == ExpandableLayout.State.COLLAPSED) {
                mToggleTv.setText("查看更多");
                mExpandHintIv.setImageResource(R.drawable.ic_expande_hint);
            } else if (state == ExpandableLayout.State.EXPANDED) {
                mToggleTv.setText("收起");
                mExpandHintIv.setImageResource(R.drawable.ic_collapse_hint);
            }
        });
        mExpandableLayout.collapse();

        mToggleWrapper = findViewById(R.id.toggle_wrapper);
        mToggleWrapper.setOnClickListener(view -> mExpandableLayout.toggle());

        mTabLayout = (SlidingTabLayout) findViewById(R.id.tab_layout);

        mContentViewPager = (ViewPager) findViewById(R.id.bottom_view_pager);

        mPagerAdapter = new ContentPagerAdapter(getSupportFragmentManager());
        mContentViewPager.setAdapter(mPagerAdapter);

        findViewById(R.id.left_action_wrapper).setOnClickListener(view -> {
            Log.i(TAG, "product image id is : " + mProduct.getImageId());
            if (TextUtils.isEmpty(mProduct.getImageId()) || TextUtils.equals(mProduct.getImageId(), "0")) {
                JUtils.ToastLong("该商品缺少图片信息，无法查找相似");
                return;
            }
            if (!TextUtils.isEmpty(mProduct.getCategoryId())) {
                ClassificationManager.getInstance().changeToSimilarMode(mProduct.getImageId(), mProduct.getCategoryId());
                Intent intent = new Intent(ProductDetailActivity.this, ProductionSummaryActivity.class);
                startActivity(intent);
                finish();
            } else {
                ClassificationManager.getInstance().changeToSimilarMode(mProduct.getImageId(), "-1");
                Intent intent = new Intent(ProductDetailActivity.this, ProductionSummaryActivity.class);
                startActivity(intent);
                finish();
//                JUtils.ToastLong("当前商品无分类，无法查找相似");
            }
        });

        mDiffTv = (TextView) findViewById(R.id.right_action_tv);
        mDownloadWrapper = (ViewGroup) findViewById(R.id.download_wrapper);
        mDownloadWrapper.setOnClickListener(view -> {
            if (mProduct == null) {
                return;
            }

            final KProgressHUD downloadDialog = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setCancellable(false)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f)
                    .show();

            Subscription subscription = NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                    .getProductDetailImage(String.valueOf(mProduct.getId()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(s -> {
                        JUtils.Log("result str is : " + s.getUrl());
                        if (TextUtils.isEmpty(s.getUrl())) {
                            JUtils.ToastLong("图片地址为空，无法下载");
                        } else {
                            JUtils.ToastLong("文件正在下载到手机Download文件夹中,请在通知栏查看下载进度");
                            String filename = mProduct.getPNO() + "详情.png";
                            DownloadManager dm = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
                            Uri downloadUri = Uri.parse(s.getUrl());
                            DownloadManager.Request request = new DownloadManager.Request(downloadUri);
                            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                                    .setAllowedOverRoaming(false)
                                    .setTitle(filename)
                                    .setMimeType("image/jpeg")
                                    .setDestinationInExternalPublicDir("/Download/", filename)
                                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                            dm.enqueue(request);
                        }
                    }, throwable -> {
                        downloadDialog.dismiss();
                        String errorMsg = "未找到下载链接";
                        ErrorHandler.handlerNetworError(throwable, errorMsg);
                        JUtils.Log("get detail image error : " + throwable.getMessage());
                        throwable.printStackTrace();
                    }, () -> {
                        downloadDialog.dismiss();
                        JUtils.Log("load detail image completely.");
                    });
            mCompositeSubscription.add(subscription);
        });

        loadData();
        ProductSummaryManager.getInstance().addProductCheckChangeListener(this);
    }

    private void loadData() {
        if (mProduct != null && mStorageList !=null) {
            bindProduct(mProduct,mStorageList);
        } else {
            final KProgressHUD hubDialog = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setCancellable(false)
                    .setAnimationSpeed(2)
                    .setDimAmount(0.5f)
                    .show();

            NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                    .getProductDetailInfo(String.valueOf(mProductId))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(productWrapper -> {
                        JUtils.Log("product load successfully, params size is : " + productWrapper.getProduct().getParameters().size());
                        mProduct = productWrapper.getProduct();
                        mStorageList = productWrapper.getStorage();
                        JUtils.Log("mStorageList 1 size is : " + mStorageList.size() );
                        bindProduct(mProduct,mStorageList);
                        JUtils.Log("mStorageList 2 size is : " + mStorageList.size() );
                        mProduct.setStorages(mStorageList);
                    }, throwable -> {
                        String errorMsg = "加载失败，请检查网络状态";
                        ErrorHandler.handlerNetworError(throwable, errorMsg);
                        JUtils.Log("load product info error : " + throwable.getMessage());
                        hubDialog.dismiss();
                        throwable.printStackTrace();
                        finish();
                    }, hubDialog::dismiss);

        }
    }

    private void initSatificationTv() {
        String currentMode = ClassificationManager.getInstance().getExtralMode();
        if (!TextUtils.equals(currentMode, ClassificationManager.MODE_EXTRA_KEY_RECOGNITION)) {
            mSatificationTv.setVisibility(View.GONE);
            return;
        }
        Subscription subscription = NetworkManager.getInstance().getRetrofit().create(ProductService.class)
                .getClientId()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                            JUtils.Log("result is :" + s.getClientId());
                            if (!TextUtils.equals(s.getClientId(), "default")) {
                                mSatificationTv.setVisibility(View.VISIBLE);
                            } else {
                                mSatificationTv.setVisibility(View.GONE);
                            }
                        },
                        throwable -> {
                            String errorMsg = "";
                            ErrorHandler.handlerNetworError(throwable, errorMsg);
                            JUtils.Log("get client id error : " + throwable.getMessage());
                            mSatificationTv.setVisibility(View.GONE);
                        });
        mCompositeSubscription.add(subscription);
    }


    private void bindProduct(Product product ,List<Storage> Storagelist) {
        mTitleTv.setText(product.getPNO());
        mProductCoverView.bindProductInfo(product);
        mProductSerialNumTv.setText("产品编号 " + product.getPNO());

        initSatificationTv();

        LinearLayout outerLL = (LinearLayout) findViewById(R.id.outer_ll);
        LinearLayout innerLL = (LinearLayout) findViewById(R.id.inner_ll);

        outerLL.setVisibility(View.VISIBLE);
        String classificationId = product.getCategoryId();
        if (!TextUtils.isEmpty(classificationId)) {
            Subscription subscription = Observable.just(classificationId)
                    .doOnNext(s -> ClassificationManager.getInstance().loadClassificationInfo(false)
                            .toBlocking()
                            .subscribe())
                    .flatMap(s -> {
                        JUtils.Log(TAG, "product classification Id is : " + classificationId);
                        String allPathName = ClassificationManager.getInstance().getClassificationName(classificationId);
                        JUtils.Log(TAG, "product classification full name is : " + allPathName);
                        String classificationName = allPathName;

                        if (allPathName.contains("\\")) {
                            String[] path = allPathName.split("\\\\");
                            classificationName = path[path.length - 1];
                        }
                        return Observable.just(classificationName);
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(name -> {
                        ProductDetailSectionView classificationSectionView = new ProductDetailSectionView(ProductDetailActivity.this);
                        classificationSectionView.bindContent("商品分类", name);
                        outerLL.addView(classificationSectionView, 0);
                    }, throwable -> {
                        ErrorHandler.handlerNetworError(throwable, "");
                        JUtils.Log(TAG, "load classification name error.");
                        throwable.printStackTrace();
                    });
            mCompositeSubscription.add(subscription);
        } else {
            ProductDetailSectionView classificationSectionView = new ProductDetailSectionView(this);
            classificationSectionView.bindContent("商品分类", "未分类商品");
            outerLL.addView(classificationSectionView, 0);
        }

        List<Parameter> parameters = product.getParameters();
        Iterator<Parameter> iterator = parameters.iterator();
        while (iterator.hasNext()) {
            Parameter item = iterator.next();
            if (TextUtils.isEmpty(item.getProductparameters().getValue())) {
                iterator.remove();
            }
        }

        if (parameters.size() == 0) {
//            outerLL.setVisibility(View.GONE);
            mExpandableLayout.setVisibility(View.GONE);
            mToggleWrapper.setVisibility(View.GONE);
        } else if (parameters.size() > 4) {
            mExpandableLayout.setVisibility(View.VISIBLE);
            mToggleWrapper.setVisibility(View.VISIBLE);
            List<Parameter> outerParams = parameters.subList(0, 4);
            List<Parameter> innerParams = parameters.subList(4, parameters.size());
            for (Parameter parameter : outerParams) {
                ProductDetailSectionView paramSectionView = new ProductDetailSectionView(this);
                paramSectionView.bindParameter(parameter);
                outerLL.addView(paramSectionView);
            }

            for (Parameter parameter : innerParams) {
                ProductDetailSectionView paramSectionView = new ProductDetailSectionView(this);
                paramSectionView.bindParameter(parameter);
                innerLL.addView(paramSectionView);
            }

        } else {
            mExpandableLayout.setVisibility(View.GONE);
            mToggleWrapper.setVisibility(View.GONE);
            for (Parameter parameter : parameters) {
                ProductDetailSectionView paramSectionView = new ProductDetailSectionView(this);
                paramSectionView.bindParameter(parameter);
                outerLL.addView(paramSectionView);
            }
        }

        List<Fragment> fragments = new ArrayList<>();

        ArrayList<Photo> photos = new ArrayList<>();
        photos.addAll(product.getPhotos());
        ProductImageFragment imageFragment = ProductImageFragment.getInstance(photos, mProduct.getPNO());
        fragments.add(imageFragment);

        ArrayList<Shelf> shelves = new ArrayList<>();
        shelves.addAll(product.getShelves());
        ShelfFragment shelfFragment = ShelfFragment.getInstance(shelves);
        fragments.add(shelfFragment);

        ArrayList<Storage> storages = (ArrayList<Storage>) Storagelist;
//        storages.addAll(storages);
        StockInfoFragment stockInfoFragment = StockInfoFragment.getInstance(storages);
        fragments.add(stockInfoFragment);

        String[] mTitles = new String[3];
        mTitles[0] = String.format("商品图片(%d)", photos.size());
        mTitles[1] = String.format("样品库(%d)", product.getShelves().size());
        mTitles[2] = String.format("仓储(%d)", storages.size());

        mPagerAdapter.bindData(fragments, mTitles);
        mTabLayout.setViewPager(mContentViewPager, mPagerAdapter.getTitles());

        if (ProductSummaryManager.getInstance().getCheckedProudctIdList().contains(product.getId())) {
            mDiffTv.setText("移除对比");
            mDiffTv.setBackgroundColor(Color.parseColor("#ced0dc"));
        } else {
            mDiffTv.setText("加入对比");
            mDiffTv.setBackgroundColor(Color.parseColor("#64a2f0"));
        }
        mDiffTv.setOnClickListener(view -> {
            if (mProduct == null) {
                return;
            }
            if (ProductSummaryManager.getInstance().getCheckedProudctIdList().contains(mProduct.getId())) {
                ProductSummaryManager.getInstance().removeProductChecked(mProduct);
                mDiffTv.setText("加入对比");
                mDiffTv.setBackgroundColor(Color.parseColor("#64a2f0"));
            } else {
                ProductSummaryManager.getInstance().addProductToCheck(mProduct);
                mDiffTv.setText("移除对比");
                mDiffTv.setBackgroundColor(Color.parseColor("#ced0dc"));
            }
        });
    }


    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    @Override
    protected void onDestroy() {
        mCompositeSubscription.clear();
        ProductSummaryManager.getInstance().removeProductCheckChangeListener(this);
        super.onDestroy();
    }

    @Override
    public void OnProductCheckChanged(int count) {
        if (mProduct != null) {
            if (ProductSummaryManager.getInstance().getCheckedProudctIdList().contains(mProduct.getId())) {
                mDiffTv.setText("移除对比");
                mDiffTv.setBackgroundColor(Color.parseColor("#ced0dc"));
            } else {
                mDiffTv.setText("加入对比");
                mDiffTv.setBackgroundColor(Color.parseColor("#64a2f0"));
            }
        }
    }
}
